import http from "@/utils/ajax/http";
import api from "@/api";
import {findIndex, findObject} from "@/utils/utils";
import date from "@/utils/date";
import { isObject} from "@/utils/extend";
import {updateChat,handlerMsg} from '@/components/chats/utils'
import rule from "@/utils/rule";
import bus from '../../components/chats/bus'

const state = {
    // 会话列表
    currentSessionTime:'',
    sessionList:[],
    currentChat:null,
    status:false,
    visibleModel:false
};

var timer;
var timeout = 10 * 1000;
var chatMessageTime = 5 * 1000;

const actions = {
    // 获取session列表
    updateSessionList(content , data){
        return new Promise((resolve, reject) => {
            if(data.type == 'new'){
                if(content.state.currentSessionTime){
                    data.lastdate = content.state.currentSessionTime;
                }else{
                    data.type = 'one';

                }

            }
            http.post("/api/chat/sessionList" , data).json().then(res=>{
                if(res.code == 0){
                    if(data.type == 'one'){
                        content.commit('setList' , res.data);
                    }else if(data.type == 'new'){
                        content.commit('updateList' , res.data);
                    }
                }
                resolve(res)
            }).catch(reject);
        });
    },
    check(ctx , {sid,rid}){
        return new Promise((resolve, reject) => {
            http.post("/api/chat/check" , {sid,rid}).json().then(res=>{
                var siliao = res.data;
                ctx.dispatch("updateSessionList" ,{
                    sid:sid,
                    type:'new'
                }).then(r=>{
                    var chat = findObject(ctx.state.sessionList , r=>r.id == siliao.id);
                    ctx.dispatch('selectChat' , chat);
                    ctx.commit('showModel');
                });

            });
        });
    },
    login(content)
    {
        var session = content.rootState.user.session;
        //if(session.cx != '管理员'){
        content.dispatch("updateSessionList" ,{
            sid:session.username,
            type:'one'
        }).then(res=>{
            content.state.status = true;
            timer = setTimeout(()=>{
                content.dispatch("loopUpdateSessionList");
            },timeout);
        });
        //}
    },
    logout(content){
        if(content.state.status){
            content.state.status = false;
            clearTimeout(timer);
            content.commit('clearChat');
            content.commit('clearSessionList');
        }
    },
    loopUpdateSessionList(content){
        var session = content.rootState.user.session;
        return new Promise((resolve, reject) => {
            content.dispatch("updateSessionList" ,{
                sid:session.username,
                type:'new'
            }).then(res=>{
                if(content.state.status){
                    timer = setTimeout(()=>{
                        content.dispatch("loopUpdateSessionList");
                    },timeout);
                }
                resolve(res);
            },reject);
        })
    },
    selectChat( content , chat ){
        content.commit('clearChat');
        content.commit('updateChat' , chat);
        if(chat && chat.id){
            if(chat.loading == 'loop'){
                // 则继续，
                content.dispatch("loopChatMessage",chat);
            }else{
                content.dispatch('oneChatMessage',chat);
            }

            var session = content.rootState.user.session;
            content.dispatch('updateRead' , {chat,sid:session.username});
        }
    },
    updateRead(ctx,{chat,sid}){
        http.post("/api/chat/updateRead",{chatid:chat.id,sid}).json().then(res=>{
            chat.readCount = 0;
        });
    },
    sendContent( ctx , { content , chat } ){
        var session = ctx.rootState.user.session;
        var form = {
            neirong: content,
            fasongren: session.username,
            fasongshijian: rule.date("Y-m-d H:i:s"),
            shifouzhakan: "否",
            siliaoid: chat.id,
        }
        return new Promise((resolve, reject) => {
            http.post("/api/xiaoxi/insert",form).json().then(res=>{
                if(res.code == 0){
                    var e = res.data;
                    var data = handlerMsg(e,session ,chat);
                    ctx.commit('sendContent' , {data,session,chat});
                }
                resolve(res)
            },reject);
        });
    },
    scrollChatMessage(content,chat)
    {
        return new Promise((resolve, reject) => {
            var form = {
                chatid:chat.id,
                offsetMin:chat.offsetMin,
                type:'top'
            };

            http.post('/api/chat/chatMessage',form).json().then(res=>{
                var $session = content.rootState.user.session;
                content.commit('scrollChatMessage' , {
                    list:res.data,
                    session:$session,
                    chat:chat
                });
                resolve(res);
            },reject);
        });
    },
    oneChatMessage(content,chat){
        if(chat.loading === 'loading'){
            chat.loading = 'one';
            var form = {
                pageSize:20,
                pageNumber:1,
                offsetMax:chat.offsetMax,
                type:'one',
                chatid:chat.id
            };
            http.post('/api/chat/chatMessage',form).json().then(res=>{
                var $session = content.rootState.user.session;
                content.commit('oneChatMessage' , {
                    list:res.data,
                    session:$session
                });
                chat.loading = 'loop';
                content.state.currentChat.timer = setTimeout(()=>{
                    content.dispatch("loopChatMessage");
                },chatMessageTime);
            });
        }
    },
    loopChatMessage(content){
        if(!content.state.status)return;
        var chat = content.state.currentChat;
        let params = {};
        params.pageNumber = 1;
        params.pageSize = 20;
        params.offsetMax = chat.offsetMax;
        params.type = "new";
        params.chatid = chat.id;
        http.post('/api/chat/chatMessage' , params).json().then(res=>{
            if(res.code == api.code.OK){

                // 数据转换
                var $session = content.rootState.user.session;
                //var result = [];

                // 发信人
                //var chat = content.state.currentChat;
                if(res.data.length > 0){
                    content.commit('loopChatMessage' , {
                        list:res.data,
                        session:$session
                    });
                    content.dispatch("updateRead" , {chat,sid:$session.username});
                }

                content.state.currentChat.timer = setTimeout(()=>{
                    content.dispatch("loopChatMessage");
                },chatMessageTime);

            }
        });
    },
};



const mutations = {
    showModel(state){
        state.visibleModel = true;
    },
    hideModel(state){
        state.visibleModel = false;
    },
    setModel(state,val){
        state.visibleModel = val;
    },
    sendContent(state,{data,session,chat}){
        chat.distincData.push(data.id);
        chat.data.push(data);
        if(chat.offsetMax < data.id){
            chat.offsetMax = data.id;
        }
    },
    scrollChatMessage(state,{list,session,chat}){
        list.forEach(e=>{
            if(chat.distincData.indexOf(e.id) <0){
                var data = handlerMsg(e,session,chat);
                chat.data.unshift(data);
                chat.distincData.push(e.id);
                // 修改最小偏移位
                if(chat.offsetMin > e.id){
                    chat.offsetMin = e.id;
                }
            }
        });
    },
    clearSessionList(state){
        state.sessionList = [];
        state.currentChat = null;
    },
    oneChatMessage(state,{list,session}){
        var chat = state.currentChat;
        list.forEach(e=>{
            if(state.currentChat.id == e.siliaoid){
                if(chat.offsetMax < e.id){
                    chat.offsetMax = e.id;
                }
                if(chat.distincData.indexOf(e.id) == -1){
                    var data = handlerMsg(e,session,state.currentChat);
                    chat.distincData.push(e.id);
                    chat.data.unshift(data);
                    //if(chat.offsetMin > e.id){
                    chat.offsetMin = e.id;

                }
            }
        });
        bus.$emit('loopChatMessage');
    },
    loopChatMessage( state,{list,session} ){
        var chat = state.currentChat;
        list = list.reverse();
        list.forEach(e=>{
            if(state.currentChat.id == e.siliaoid){
                if(chat.offsetMax < e.id){
                    chat.offsetMax = e.id;
                }
                if(chat.distincData.indexOf(e.id) == -1){
                    var data = handlerMsg(e,session,state.currentChat);
                    chat.distincData.push(e.id);
                    chat.data.push(data);
                }
            }
        });
        bus.$emit('loopChatMessage');
    },
    clearChat(state){
        for (var co of state.sessionList){
            if(co.timer){
                clearTimeout(co.timer);
                co.timer = null;
            }
        }
    },
    updateChat(state , chat){
        state.currentChat = chat;
    },
    setList(state,list){
        for (var co of list){
            updateChat(co);
        }
        if(list.length > 0){
            state.currentSessionTime = list[list.length-1].xiaoxizuihoushijian;
        }else{
            state.currentSessionTime = date("Y-m-d H:i:s");
        }
        state.sessionList = list.sort((a,b)=>{
            if(b.addtime == a.addtime){
                return 0;
            }
            return b.addtime > a.addtime ? 1 : -1;
        });

    },
    updateList(state,list){
        for (var co of list){
            var index = findIndex(state.sessionList , r=>r.id == co.id);
            if(index !== false){
                var newData = state.sessionList.splice(index , 1)[0];
                newData.readCount = co.readCount;
                state.sessionList.unshift(newData);
            }else{
                updateChat(co);
                state.sessionList.unshift(co);
            }
            state.currentSessionTime = co.xiaoxizuihoushijian;
        }
    }
};

const getters = {
    readCount:state=>{
        var readCount = 0;
        for (var co of state.sessionList){
            readCount += co.readCount;
        }
        return readCount;
    }
}

export default {
    namespaced: true,
    state,
    actions,
    mutations,
    getters
};
